import datetime
import glob
import os.path
import subprocess

from config import env


def run_cmd_realtime(cmd):
    # 创建子进程，stdout和stderr合并到一起
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=True,
        text=True,   # Python 3.7+，等同于 universal_newlines=True，输出字符串而非字节
        bufsize=1    # 行缓冲
    )

    # 按行实时打印输出
    for line in process.stdout:
        print(line, end='')  # line本身带换行符，不要再加

    process.stdout.close()
    process.wait()  # 等待进程结束
    print(f"\n进程退出，返回码：{process.returncode}")


def build_cmd():
    resource_list = [os.path.abspath(file) for file in glob.glob("./resource/*")]


    u2 = [os.path.abspath(".\\.venv\\Lib\\site-packages\\uiautomator2\\assets\\u2.jar")]

    cmd = f"pyinstaller --onefile --noconsole --name=小小帝国.{env}.{datetime.datetime.now().strftime('%Y%m%d%H%M%S')} --distpath dist main.py"

    # 添加图标
    icon_path = os.path.abspath('./resource/icon_cleaned.ico')
    cmd += f' --icon="{icon_path}"'

    # 图片识别依赖的模板
    for resource in resource_list:
        cmd += f' --add-data "{resource}:resource"'

    # uiautomator2依赖的jar包
    for resource in u2:
        cmd += f' --add-data "{resource}:uiautomator2\\assets"'

    # Vosk依赖的模型文件
    cmd += f' --add-data "{resource}:vosk"'
    for lib in ['libvosk.dll']:
        lib_path = os.path.abspath(f".\\.venv\\Lib\\site-packages\\vosk\\{lib}")
        cmd += f' --add-data "{lib_path}:vosk"'

    cmd += f' --add-data "{os.path.abspath('./white_list.json.enc')}:/"'

    # cmd += f' --add-data "{os.path.abspath("./vosk-model-small-cn-0.22")}:vosk-model-small-cn-0.22"'
    return cmd

cmd = build_cmd()
print(cmd)
run_cmd_realtime(cmd)